{% extends "templates/web.html" %}

{% block page_content %}
<style>
/* 基于YunExpress设计的TMS跟踪界面样式 */
.tracking-container {
    width: 100vw;
    height: 100vh;
    margin: 0;
    padding: 0;
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
    background: #f8f9fa;
    display: flex;
    flex-direction: column;
    overflow: hidden;
}

/* 顶部搜索区域 */
.tracking-search {
    background: white;
    padding: 20px;
    border-radius: 0;
    margin: 0;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    display: flex;
    gap: 15px;
    align-items: center;
    flex-shrink: 0;
}

.tracking-search .input-group {
    flex: 1;
    position: relative;
}

.tracking-search input {
    width: 100%;
    padding: 12px 16px;
    border: 2px solid #e9ecef;
    border-radius: 6px;
    font-size: 16px;
    transition: border-color 0.3s;
}

.tracking-search input:focus {
    outline: none;
    border-color: #007bff;
}

.tracking-search button {
    background: #dc3545;
    color: white;
    border: none;
    padding: 12px 24px;
    border-radius: 6px;
    font-size: 16px;
    cursor: pointer;
    transition: background-color 0.3s;
    font-weight: 600;
}

.tracking-search button:hover {
    background: #c82333;
}

/* 状态筛选区域 */
.status-filter {
    background: white;
    padding: 15px 20px;
    border-radius: 0;
    margin: 0;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-shrink: 0;
}

.filter-tabs {
    display: flex;
    gap: 20px;
    align-items: center;
}

.filter-tab {
    padding: 8px 16px;
    border-radius: 20px;
    cursor: pointer;
    transition: all 0.3s;
    font-size: 14px;
    font-weight: 500;
    display: flex;
    align-items: center;
    gap: 8px;
}

.filter-tab.active {
    background: #dc3545;
    color: white;
}

.filter-tab:not(.active) {
    background: #f8f9fa;
    color: #6c757d;
}

.filter-tab:not(.active):hover {
    background: #e9ecef;
    color: #495057;
}

.filter-tab .icon {
    font-size: 16px;
}

.export-btn {
    background: #dc3545;
    color: white;
    border: none;
    padding: 8px 16px;
    border-radius: 6px;
    cursor: pointer;
    font-size: 14px;
    font-weight: 500;
    display: flex;
    align-items: center;
    gap: 8px;
}

.export-btn:hover {
    background: #c82333;
}

/* 跟踪结果表格 */
.tracking-results {
    background: white;
    border-radius: 0;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    overflow: hidden;
    flex: 1;
    display: flex;
    flex-direction: column;
}

.tracking-table {
    width: 100%;
    border-collapse: collapse;
    flex: 1;
    display: flex;
    flex-direction: column;
}

.tracking-table thead {
    background: #28a745;
    color: white;
    flex-shrink: 0;
    display: table;
    width: 100%;
    table-layout: fixed;
}

.tracking-table th {
    padding: 15px 12px;
    text-align: left;
    font-weight: 600;
    font-size: 14px;
}

.tracking-table tbody {
    flex: 1;
    overflow-y: auto;
    display: block;
}

.tracking-table tbody tr {
    border-bottom: 1px solid #e9ecef;
    cursor: pointer;
    transition: all 0.3s ease;
    position: relative;
    display: table;
    width: 100%;
    table-layout: fixed;
}

.tracking-table tbody tr:hover {
    background: #f8f9fa;
    transform: translateY(-1px);
    box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.tracking-table tbody tr:active {
    transform: translateY(0);
    box-shadow: 0 1px 4px rgba(0,0,0,0.1);
}

.tracking-table tbody tr.selected {
    background: #e8f5e8;
    border-left: 4px solid #28a745;
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(40, 167, 69, 0.2);
}

.tracking-table tbody tr.selected:hover {
    background: #d4edda;
    transform: translateY(-3px);
    box-shadow: 0 6px 16px rgba(40, 167, 69, 0.3);
}

.tracking-table td {
    padding: 15px 12px;
    vertical-align: top;
}

.tracking-number {
    font-weight: 600;
    color: #007bff;
    font-size: 14px;
}

.tracking-route {
    font-size: 12px;
    color: #6c757d;
    margin-top: 4px;
}

.status-badge {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    padding: 4px 12px;
    border-radius: 12px;
    font-size: 12px;
    font-weight: 500;
}

.status-badge.delivered {
    background: #d4edda;
    color: #155724;
}

.status-badge.processing {
    background: #fff3cd;
    color: #856404;
}

.status-badge.transit {
    background: #cce5ff;
    color: #004085;
}

.status-badge.not-found {
    background: #f8d7da;
    color: #721c24;
}

.status-badge.alert {
    background: #f5c6cb;
    color: #721c24;
}

.status-badge.returned {
    background: #e2e3e5;
    color: #383d41;
}

.last-event {
    font-size: 13px;
    color: #495057;
    line-height: 1.4;
}

/* 展开的详细信息 */
.tracking-detail {
    display: none;
    background: #f8f9fa;
    border-top: 1px solid #e9ecef;
    animation: slideDown 0.3s ease-out;
}

.tracking-detail.expanded {
    display: table-row;
    animation: slideDown 0.3s ease-out;
}

@keyframes slideDown {
    from {
        opacity: 0;
        max-height: 0;
        transform: translateY(-10px);
    }
    to {
        opacity: 1;
        max-height: 500px;
        transform: translateY(0);
    }
}

.detail-actions {
    padding: 15px 20px;
    border-bottom: 1px solid #e9ecef;
    display: flex;
    gap: 10px;
}

.detail-btn {
    background: #6c757d;
    color: white;
    border: none;
    padding: 6px 12px;
    border-radius: 4px;
    font-size: 12px;
    cursor: pointer;
}

.detail-btn:hover {
    background: #5a6268;
}

.detail-content {
    display: grid;
    grid-template-columns: 2fr 1fr;
    gap: 20px;
    padding: 20px;
}

.timeline-section h4 {
    margin: 0 0 15px 0;
    color: #333;
    font-size: 16px;
    font-weight: 600;
}

.timeline-item {
    display: flex;
    align-items: flex-start;
    margin-bottom: 15px;
    position: relative;
    padding-left: 20px;
}

.timeline-item:not(:last-child)::before {
    content: '';
    position: absolute;
    left: 8px;
    top: 20px;
    bottom: -15px;
    width: 2px;
    background: #e9ecef;
}

.timeline-item::after {
    content: '';
    position: absolute;
    left: 6px;
    top: 16px;
    width: 6px;
    height: 6px;
    border-radius: 50%;
    background: #6c757d;
}

.timeline-content {
    flex: 1;
}

.timeline-time {
    font-size: 13px;
    color: #6c757d;
    margin-bottom: 4px;
}

.timeline-event {
    font-size: 14px;
    color: #333;
    font-weight: 500;
}

.timeline-location {
    font-size: 13px;
    color: #6c757d;
    margin-top: 4px;
}

.sidebar-section h4 {
    margin: 0 0 15px 0;
    color: #333;
    font-size: 16px;
    font-weight: 600;
}

.info-row {
    display: flex;
    justify-content: space-between;
    margin-bottom: 10px;
    padding-bottom: 10px;
    border-bottom: 1px solid #e9ecef;
}

.info-row:last-child {
    margin-bottom: 0;
    padding-bottom: 0;
    border-bottom: none;
}

.info-label {
    color: #6c757d;
    font-size: 13px;
}

.info-value {
    color: #333;
    font-size: 13px;
    font-weight: 500;
}

.info-value a {
    color: #007bff;
    text-decoration: none;
}

.info-value a:hover {
    text-decoration: underline;
}

/* 加载和错误状态 */
.loading {
    text-align: center;
    padding: 40px;
    color: #6c757d;
}

.error {
    background: #f8d7da;
    color: #721c24;
    padding: 15px;
    border-radius: 6px;
    margin: 20px 0;
    border: 1px solid #f5c6cb;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .tracking-container {
        padding: 0;
    }
    
    .tracking-search {
        flex-direction: column;
        padding: 15px;
    }
    
    .status-filter {
        flex-direction: column;
        gap: 15px;
        align-items: stretch;
        padding: 15px;
    }
    
    .filter-tabs {
        flex-wrap: wrap;
        gap: 10px;
    }
    
    .detail-content {
        grid-template-columns: 1fr;
    }
    
    .tracking-table {
        font-size: 12px;
    }
    
    .tracking-table th,
    .tracking-table td {
        padding: 10px 8px;
    }
}
</style>

<div class="tracking-container">
    
    <!-- 搜索区域 -->
    <div class="tracking-search">
            <div class="input-group">
            <input type="text" id="trackingInput" placeholder="输入跟踪号" value="">
        </div>
        <button id="trackBtn">Track</button>
    </div>

    <!-- 状态筛选区域 -->
    <div class="status-filter">
        <div class="filter-tabs">
            <div class="filter-tab active" data-status="all">
                <span class="icon">📦</span>
                <span>All(<span id="allCount">0</span>)</span>
                </div>
            <div class="filter-tab" data-status="processing">
                <span class="icon">⚙</span>
                <span>Processing(<span id="processingCount">0</span>)</span>
                    </div>
            <div class="filter-tab" data-status="transit">
                <span class="icon">✈</span>
                <span>Transit(<span id="transitCount">0</span>)</span>
                </div>
            <div class="filter-tab" data-status="delivered">
                <span class="icon">✓</span>
                <span>Delivered(<span id="deliveredCount">0</span>)</span>
                </div>
            <div class="filter-tab" data-status="not-found">
                <span class="icon">✗</span>
                <span>Not Found(<span id="notFoundCount">0</span>)</span>
                </div>
            <div class="filter-tab" data-status="alert">
                <span class="icon">⚠</span>
                <span>Alert(<span id="alertCount">0</span>)</span>
                </div>
            <div class="filter-tab" data-status="returned">
                <span class="icon">↻</span>
                <span>Returned(<span id="returnedCount">0</span>)</span>
            </div>
        </div>
        <button class="export-btn" id="exportBtn">
            <span>📋</span>
            <span>Copy & Export</span>
        </button>
            </div>

    <!-- 跟踪结果表格 -->
    <div id="trackingResults" class="tracking-results" style="display: none;">
        <table class="tracking-table">
            <thead>
                <tr>
                    <th>Tracking Number</th>
                    <th>Delivery Status</th>
                    <th>Last Mile Tracking</th>
                    <th>Order Number</th>
                    <th>Last Event</th>
                </tr>
            </thead>
            <tbody id="trackingTableBody">
                <!-- 跟踪结果将通过JavaScript动态生成 -->
            </tbody>
        </table>
    </div>

    <!-- 加载状态 -->
    <div id="loadingState" class="loading" style="display: none;">
        <p>正在查询跟踪信息...</p>
    </div>

    <!-- 错误状态 -->
    <div id="errorState" class="error" style="display: none;">
        <p id="errorMessage">查询失败，请稍后重试</p>
    </div>
</div>

<script>
// 全局变量
let trackingData = [];
let currentFilter = 'all';

// 初始化跟踪页面
document.addEventListener('DOMContentLoaded', function() {
    console.log('===== TMS跟踪页面初始化开始 =====');
    console.log('初始化时间:', new Date().toLocaleString());
    console.log('版本: v2.1 - 云途API集成版');
    console.log('API集成: 已连接云途物流API');
    
    // 清除所有测试数据
    trackingData = [];
    clearAllResults();
    
    bindEvents();

    // 支持通过 URL 参数 ?num=FGxxxx 或 ?tracking=FGxxxx 直接查询
    try {
        const params = new URLSearchParams(window.location.search);
        const numParam = params.get('num') || params.get('tracking');
        if (numParam) {
            const inputEl = document.getElementById('trackingInput');
            if (inputEl) inputEl.value = numParam;
            handleTrack();
        }
    } catch (e) {}
    console.log('===== TMS跟踪页面初始化完成 =====');
    console.log('页面已准备就绪，可以开始真实跟踪查询');
});

// 清除所有结果显示
function clearAllResults() {
    // 隐藏结果表格
    const resultsDiv = document.getElementById('trackingResults');
    if (resultsDiv) {
        resultsDiv.style.display = 'none';
    }
    
    // 清空表格内容
    const tableBody = document.getElementById('trackingTableBody');
    if (tableBody) {
        tableBody.innerHTML = '';
    }
    
    // 重置状态计数
    updateStatusCounts();
}


// 绑定事件
function bindEvents() {
    // 跟踪按钮
    const trackBtn = document.getElementById('trackBtn');
    if (trackBtn) {
        trackBtn.addEventListener('click', handleTrack);
    }

    // 跟踪输入框回车键
    const trackingInput = document.getElementById('trackingInput');
    if (trackingInput) {
        trackingInput.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                handleTrack();
            }
        });
    }

    // 状态筛选标签
    const filterTabs = document.querySelectorAll('.filter-tab');
    filterTabs.forEach(tab => {
        tab.addEventListener('click', function() {
            const status = this.dataset.status;
            setActiveFilter(status);
            filterTrackingResults(status);
        });
    });

    // 导出按钮
    const exportBtn = document.getElementById('exportBtn');
    if (exportBtn) {
        exportBtn.addEventListener('click', handleExport);
    }
}

// 处理多个跟踪号查询
async function handleTrack() {
    const input = document.getElementById('trackingInput').value.trim();

    if (!input) {
        showError('请输入跟踪号');
        return;
    }

    // 解析多个跟踪号（用分号分隔）
    const trackingNumbers = input.split(';').map(num => num.trim()).filter(num => num.length > 0);
    
    if (trackingNumbers.length === 0) {
        showError('请输入有效的跟踪号');
        return;
    }

    // 显示加载状态
    showLoading();

    try {
        // 调用云途API获取跟踪信息
        const apiResponse = await frappe.call({
            method: 'upsystem.upsystem.api.batch_tracking',
            args: {
                tracking_numbers: trackingNumbers
            }
        });

        if (apiResponse && apiResponse.message && apiResponse.message.success) {
            // 处理API返回的数据，转换为表格格式
            const results = apiResponse.message.data || [];
            
            trackingData = results.map(result => {
                if (result.success && result.data) {
                    const item = result.data;
                    return {
                        trackingNumber: result.tracking_number || '',
                        status: item.status || 'unknown',
                        deliveryStatus: getStatusInfo(item.status || 'unknown'),
                        lastMileTracking: item.last_mile_tracking || '-',
                        orderNumber: item.order_number || '-',
                        lastEvent: item.last_event || '查询中...',
                        route: item.route || 'CN → Unknown',
                        trackingHistory: item.tracking_history || [],
                        carrierInfo: item.carrier_info || {
                            name: '云途物流',
                            website: 'https://www.yunexpress.com',
                            email: 'service@yunexpress.com',
                            phone: '+86 400-123-4567'
                        },
                        success: true
                    };
                } else {
                    return {
                        trackingNumber: result.tracking_number || '',
                        status: 'error',
                        deliveryStatus: getStatusInfo('error'),
                        lastMileTracking: '-',
                        orderNumber: '-',
                        lastEvent: result.message || '查询失败',
                        route: 'CN → Unknown',
                        trackingHistory: [],
                        carrierInfo: {
                            name: '云途物流',
                            website: 'https://www.yunexpress.com',
                            email: 'service@yunexpress.com',
                            phone: '+86 400-123-4567'
                        },
                        success: false
                    };
                }
            });

            // 显示结果
            showMultipleTrackingResults();
            updateStatusCounts();
            
        } else {
            const errorMsg = apiResponse?.message?.message || '获取跟踪信息失败';
            showError(errorMsg);
        }
    } catch (error) {
        showError('网络错误，请稍后重试: ' + error.message);
    }
}

// 云途API数据处理函数（已集成到handleTrack中）

// 显示多个跟踪结果
function showMultipleTrackingResults() {
    // 隐藏加载和错误状态
    document.getElementById('loadingState').style.display = 'none';
    document.getElementById('errorState').style.display = 'none';

    // 生成表格行
    generateTrackingTable();

    // 显示结果
    document.getElementById('trackingResults').style.display = 'block';
}

// 生成跟踪表格
function generateTrackingTable() {
    const tbody = document.getElementById('trackingTableBody');
    tbody.innerHTML = '';

    trackingData.forEach((item, itemIndex) => {
        const row = document.createElement('tr');
        row.className = 'tracking-row';
        row.dataset.status = item.status;
        row.dataset.index = itemIndex;
        
        row.innerHTML = `
            <td>
                <div class="tracking-number">${item.trackingNumber}</div>
                <div class="tracking-route">${item.route}</div>
            </td>
            <td>
                <div class="status-badge ${item.deliveryStatus.class}">
                    <span>${item.deliveryStatus.icon}</span>
                    <span>${item.deliveryStatus.text}</span>
                </div>
            </td>
            <td>${item.lastMileTracking}</td>
            <td>${item.orderNumber}</td>
            <td>
                <div class="last-event">${item.lastEvent}</div>
            </td>
        `;

        // 添加点击事件
        row.addEventListener('click', function(e) {
            toggleTrackingDetail(itemIndex);
        });
        
        // 添加鼠标悬停效果
        row.addEventListener('mouseenter', function() {
            // 可以在这里添加悬停效果
        });

        tbody.appendChild(row);

        // 添加详细信息行
        const detailRow = document.createElement('tr');
        detailRow.className = 'tracking-detail';
        detailRow.dataset.index = itemIndex;
        detailRow.innerHTML = `
            <td colspan="5">
                <div class="detail-actions">
                    <button class="detail-btn" onclick="copyTrackingHistory(${itemIndex})">Copy Tracking History</button>
                    <button class="detail-btn" onclick="copyLink(${itemIndex})">Copy Link</button>
                </div>
                <div class="detail-content">
                    <div class="timeline-section">
                        <h4>Tracking History</h4>
                        <div class="timeline-container" id="timeline-${itemIndex}">
                            <!-- 时间线将通过JavaScript生成 -->
                        </div>
                    </div>
                    <div class="sidebar-section">
                        <h4>Shipment Information</h4>
                        <div class="info-row">
                            <span class="info-label">Order Number</span>
                            <span class="info-value">${item.orderNumber}</span>
                        </div>
                        <div class="info-row">
                            <span class="info-label">Country</span>
                            <span class="info-value">${item.route}</span>
                        </div>
                        <h4>Additional Notes</h4>
                        <div class="info-row">
                            <span class="info-label">Last Mile</span>
                            <span class="info-value">${item.carrierInfo.name || 'Unknown'}</span>
                        </div>
                        <div class="info-row">
                            <span class="info-label">Last Mile Website</span>
                            <span class="info-value">
                                ${item.carrierInfo.website ? 
                                    `<a href="${item.carrierInfo.website}" target="_blank">${item.carrierInfo.website}</a>` : 
                                    'N/A'}
                            </span>
                        </div>
                        <div class="info-row">
                            <span class="info-label">Contact Email</span>
                            <span class="info-value">${item.carrierInfo.email || 'N/A'}</span>
                        </div>
                        <div class="info-row">
                            <span class="info-label">Contact Phone</span>
                            <span class="info-value">${item.carrierInfo.phone || 'N/A'}</span>
                        </div>
                        <div class="info-row">
                            <span class="info-label">Working Hours</span>
                            <span class="info-value">${item.carrierInfo.working_hours || 'N/A'}</span>
                        </div>
                    </div>
                </div>
            </td>
        `;

        tbody.appendChild(detailRow);

        // 生成时间线
        generateTimelineForItem(itemIndex, item.trackingHistory);
    });
}

// 生成单个包裹的时间线
function generateTimelineForItem(itemIndex, historyData) {
    const containerId = 'timeline-' + itemIndex;
    const container = document.getElementById(containerId);
    
    if (!container) {
        return;
    }

    container.innerHTML = '';
    
    if (!historyData || !Array.isArray(historyData)) {
        container.innerHTML = '<p>暂无跟踪历史</p>';
        return;
    }
    
    // 将历史数据倒序排列，最新的事件在最前面
    const reversedHistoryData = [...historyData].reverse();
    
    reversedHistoryData.forEach((item, itemIndex) => {
        const timelineItem = document.createElement('div');
        timelineItem.className = 'timeline-item';
        
        const formattedTime = formatTimelineTime(item.timestamp);
        
        timelineItem.innerHTML = `
            <div class="timeline-content">
                <div class="timeline-time">${formattedTime}</div>
                <div class="timeline-event">${item.description || item.event}</div>
                ${item.location ? `<div class="timeline-location">${item.location}</div>` : ''}
            </div>
        `;
        
        container.appendChild(timelineItem);
    });
}

// 切换跟踪详情显示
function toggleTrackingDetail(index) {
    if (index === undefined || index === null || isNaN(index)) {
        return;
    }
    
    const rows = document.querySelectorAll('.tracking-row');
    const detailRows = document.querySelectorAll('.tracking-detail');
    
    // 移除所有选中状态
    rows.forEach(row => row.classList.remove('selected'));
    detailRows.forEach(row => row.classList.remove('expanded'));
    
    // 选中当前行
    const selector = '.tracking-row[data-index="' + index + '"]';
    const detailSelector = '.tracking-detail[data-index="' + index + '"]';
    
    const currentRow = document.querySelector(selector);
    const currentDetail = document.querySelector(detailSelector);
    
    if (currentRow && currentDetail) {
        currentRow.classList.add('selected');
        currentDetail.classList.add('expanded');
    }
}

// 设置活动筛选器
function setActiveFilter(status) {
    const filterTabs = document.querySelectorAll('.filter-tab');
    filterTabs.forEach(tab => {
        tab.classList.remove('active');
        if (tab.dataset.status === status) {
            tab.classList.add('active');
        }
    });
    currentFilter = status;
}

// 筛选跟踪结果
function filterTrackingResults(status) {
    const rows = document.querySelectorAll('.tracking-row');
    const detailRows = document.querySelectorAll('.tracking-detail');
    
    rows.forEach(row => {
        const rowStatus = row.dataset.status;
        if (status === 'all' || rowStatus === status) {
            row.style.display = '';
            // 同时显示/隐藏对应的详情行
            const index = row.dataset.index;
            const detailRow = document.querySelector('.tracking-detail[data-index="' + index + '"]');
            if (detailRow) {
                detailRow.style.display = '';
            }
        } else {
            row.style.display = 'none';
            // 隐藏对应的详情行
            const index = row.dataset.index;
            const detailRow = document.querySelector('.tracking-detail[data-index="' + index + '"]');
            if (detailRow) {
                detailRow.style.display = 'none';
            }
        }
    });
}

// 更新状态计数
function updateStatusCounts() {
    const counts = {
        all: trackingData.length,
        processing: 0,
        transit: 0,
        delivered: 0,
        'not-found': 0,
        alert: 0,
        returned: 0
    };

    trackingData.forEach(item => {
        if (counts.hasOwnProperty(item.status)) {
            counts[item.status]++;
        }
    });

    // 更新UI计数
    Object.keys(counts).forEach(status => {
        const element = document.getElementById(status + 'Count');
        if (element) {
            element.textContent = counts[status];
        }
    });
}

// 获取状态信息
function getStatusInfo(status) {
    const statusMap = {
        // 基本包裹状态
        'delivered': { text: 'Delivered', icon: '✓', class: 'delivered' },
        'in_transit': { text: 'In Transit', icon: '🚚', class: 'transit' },
        'out_for_delivery': { text: 'Out for Delivery', icon: '🚛', class: 'transit' },
        'processing': { text: 'Processing', icon: '⚙', class: 'processing' },
        'pending': { text: 'Pending', icon: '⏳', class: 'processing' },
        'not-found': { text: 'Not Found', icon: '❌', class: 'not-found' },
        'exception': { text: 'Alert', icon: '⚠', class: 'alert' },
        'returned': { text: 'Returned', icon: '🔄', class: 'returned' },
        'unknown': { text: 'Unknown', icon: '❓', class: 'processing' },
        
        // 轨迹历史状态（中文）
        '订单创建': { text: '订单创建', icon: '📝', class: 'processing' },
        '已取件': { text: '已取件', icon: '📦', class: 'processing' },
        '到达始发地设施': { text: '到达始发地设施', icon: '🏭', class: 'processing' },
        '离开始发地设施': { text: '离开始发地设施', icon: '🚛', class: 'transit' },
        '到达始发机场': { text: '到达始发机场', icon: '✈️', class: 'transit' },
        '国际航班起飞': { text: '国际航班起飞', icon: '✈️', class: 'transit' },
        '清关处理中': { text: '清关处理中', icon: '🏛️', class: 'processing' },
        '国际航班到达': { text: '国际航班到达', icon: '✈️', class: 'transit' },
        '清关完成': { text: '清关完成', icon: '✅', class: 'processing' },
        '运输中': { text: '运输中', icon: '🚚', class: 'transit' },
        '到达中转站': { text: '到达中转站', icon: '🏢', class: 'transit' },
        '承运商运输中': { text: '承运商运输中', icon: '🚛', class: 'transit' },
        '派送中': { text: '派送中', icon: '🚚', class: 'transit' },
        '已送达': { text: '已送达', icon: '✓', class: 'delivered' },
        '异常': { text: '异常', icon: '⚠️', class: 'alert' },
        '已退回': { text: '已退回', icon: '🔄', class: 'returned' }
    };
    
    return statusMap[status] || { text: status, icon: '❓', class: 'processing' };
}

// 格式化时间线时间
function formatTimelineTime(timestamp) {
    if (!timestamp) return 'Unknown time';
    
    const date = new Date(timestamp);
    const options = {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
        timeZone: 'Asia/Shanghai'
    };
    
    return date.toLocaleString('zh-CN', options);
}

// 复制跟踪历史
function copyTrackingHistory(index) {
    const item = trackingData[index];
    if (!item || !item.trackingHistory) return;

    const historyText = item.trackingHistory.map(event => {
        const time = formatTimelineTime(event.timestamp);
        return `${time}: ${event.description || event.event}`;
    }).join('\n');

    navigator.clipboard.writeText(historyText).then(() => {
        alert('跟踪历史已复制到剪贴板');
    }).catch(err => {
        console.error('复制失败:', err);
    });
}

// 复制链接
function copyLink(index) {
    const item = trackingData[index];
    if (!item) return;

    const link = `${window.location.origin}${window.location.pathname}?tracking=${item.trackingNumber}`;
    
    navigator.clipboard.writeText(link).then(() => {
        alert('跟踪链接已复制到剪贴板');
    }).catch(err => {
        console.error('复制失败:', err);
    });
}

// 处理导出
function handleExport() {
    if (trackingData.length === 0) {
        alert('没有数据可导出');
        return;
    }

    // 生成CSV数据
    const csvData = generateCSV();
    
    // 创建下载链接
    const blob = new Blob([csvData], { type: 'text/csv;charset=utf-8;' });
    const link = document.createElement('a');
    const url = URL.createObjectURL(blob);
    link.setAttribute('href', url);
    link.setAttribute('download', `tracking_results_${new Date().toISOString().split('T')[0]}.csv`);
    link.style.visibility = 'hidden';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
}

// 生成CSV数据
function generateCSV() {
    const headers = ['Tracking Number', 'Status', 'Last Mile Tracking', 'Order Number', 'Last Event', 'Route'];
    const rows = trackingData.map(item => [
        item.trackingNumber,
        item.deliveryStatus.text,
        item.lastMileTracking,
        item.orderNumber,
        item.lastEvent,
        item.route
    ]);

    const csvContent = [headers, ...rows]
        .map(row => row.map(field => `"${field}"`).join(','))
        .join('\n');

    return csvContent;
}

// 显示加载状态
function showLoading() {
    document.getElementById('trackingResults').style.display = 'none';
    document.getElementById('errorState').style.display = 'none';
    document.getElementById('loadingState').style.display = 'block';
}

// 显示错误信息
function showError(message) {
    console.log('显示错误信息:', message);
    
    let errorText = message;
    if (typeof message === 'object') {
        errorText = JSON.stringify(message, null, 2);
    }
    
    document.getElementById('trackingResults').style.display = 'none';
    document.getElementById('loadingState').style.display = 'none';
    document.getElementById('errorState').style.display = 'block';
    document.getElementById('errorMessage').textContent = errorText;
}
</script>
{% endblock %}

{% block footer %}{% endblock %}